package it.mp.acquaalta.widget;

import it.mp.acquaalta.AcquaAlta;
import it.mp.acquaalta.utility.AcquaAltaBean;
import it.mp.acquaalta.utility.Allarmi;
import it.mp.acquaalta.utility.DecodificaPagina;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.widget.RemoteViews;

public class AcquaAltaService extends Service {

	private boolean onCreate = false;
	private Timer timer = new Timer();
	// private static final long UPDATE_INTERVAL = 1800000;
	// private static final long UPDATE_INTERVAL = 900000;
	private static final long UPDATE_INTERVAL = AlarmManager.INTERVAL_HOUR/2;

	BroadcastReceiver br = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			AcquaAltaBean aaBean = AcquaAltaBean.valueOf(context);
			valorizzaWidget(aaBean);
		}
	};

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		if (onCreate) {

		} else {
			_getWidgetUpdate();
		}
	}

	@Override
	public void onCreate() {
		onCreate = true;
		IntentFilter intf = new IntentFilter();
		intf.addAction("AGGIORNA_WIDGET_AA");
		registerReceiver(br, intf);
		_startService();
	}

	private void _startService() {
		timer.scheduleAtFixedRate(new TimerTask() {
			public void run() {
				_getWidgetUpdate();
			}
		}, 0, UPDATE_INTERVAL);
	}

	private void _getWidgetUpdate() {

		DecodificaPagina previsione = null;
		try {
			previsione = recuperaDati();
		} catch (Exception e) {
			e.printStackTrace();
		}

		AcquaAltaBean aa = null;
		if (previsione == null) {
			aa = AcquaAltaBean.valueOf(this);
		} else {
			aa = previsione.getBean();
			aa.toSharedPreferences(this);
		}

		valorizzaWidget(aa);
	}

	private void valorizzaWidget(AcquaAltaBean aa) {

		Intent defineIntent = new Intent(AcquaAltaService.this, AcquaAlta.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(AcquaAltaService.this, 0, defineIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		AppWidgetManager manager = AppWidgetManager.getInstance(this);
		RemoteViews updateViews = null;
		ComponentName thisWidget = new ComponentName(this, AcquaAltaAppWidgetProvider.class);
		updateViews = new RemoteViews(AcquaAltaService.this.getPackageName(), R.layout.acquaalta);

		updateViews.setOnClickPendingIntent(R.id.LL_layout, pendingIntent);

		manager.updateAppWidget(thisWidget, updateViews);

		Calendar cal = Calendar.getInstance();
		AcquaAltaBean.Bean bean = null;
		bean = aa.alBean.get(0);
		if (bean.isValorizzato()) {
			cal.set(Calendar.MILLISECOND,0);
			cal.set(Calendar.SECOND,0);
			cal.set(Calendar.MINUTE,0);
			cal.set(Calendar.HOUR,0);			
			cal.set(Calendar.YEAR, Integer.valueOf(bean.getAnno()));
			cal.set(Calendar.MONTH, Integer.valueOf(bean.getMese()) - 1);
			cal.set(Calendar.DAY_OF_MONTH, Integer.valueOf(bean.getGiorno()));
			if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
				updateViews.setImageViewResource(R.id.IV_giorno_settimana, R.drawable.dom);
			} else if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
				updateViews.setImageViewResource(R.id.IV_giorno_settimana, R.drawable.lun);
			} else if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY) {
				updateViews.setImageViewResource(R.id.IV_giorno_settimana, R.drawable.mar);
			} else if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY) {
				updateViews.setImageViewResource(R.id.IV_giorno_settimana, R.drawable.mer);
			} else if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY) {
				updateViews.setImageViewResource(R.id.IV_giorno_settimana, R.drawable.gio);
			} else if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
				updateViews.setImageViewResource(R.id.IV_giorno_settimana, R.drawable.ven);
			} else if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
				updateViews.setImageViewResource(R.id.IV_giorno_settimana, R.drawable.sab);
			}
			if ("2010".equals(bean.getAnno())) {
				updateViews.setImageViewResource(R.id.IV_anno, R.drawable.anno2010);
			} else {
				updateViews.setImageViewResource(R.id.IV_anno, R.drawable.anno2011);
			}
			updateViews.setTextViewText(R.id.TV_giorno, bean.getDataWidget());

			updateViews.setTextViewText(R.id.TV_ora_1, bean.getOrario());
			if (Integer.parseInt(bean.valore) > 0) {
				updateViews.setTextViewText(R.id.TV_val_1, "+" + bean.valore);
			} else {
				updateViews.setTextViewText(R.id.TV_val_1, bean.valore);
			}
			updateViews.setImageViewResource(R.id.IV_pallino_1, bean.getQuadratino());

			if (bean.tipo.equals("minimo")) {
				updateViews.setImageViewResource(R.id.IV_tipo_1, R.drawable.min);
				updateViews.setImageViewResource(R.id.IV_tipo_2, R.drawable.max);
			} else {
				updateViews.setImageViewResource(R.id.IV_tipo_1, R.drawable.max);
				updateViews.setImageViewResource(R.id.IV_tipo_2, R.drawable.min);
			}

			bean = aa.alBean.get(1);
			updateViews.setTextViewText(R.id.TV_ora_2, bean.getOrario());
			if (Integer.parseInt(bean.valore) > 0) {
				updateViews.setTextViewText(R.id.TV_val_2, "+" + bean.valore);
			} else {
				updateViews.setTextViewText(R.id.TV_val_2, bean.valore);
			}
			updateViews.setImageViewResource(R.id.IV_pallino_2, bean.getQuadratino());

			manager.updateAppWidget(thisWidget, updateViews);

			Allarmi a = new Allarmi(aa.alBean, this);
			a.settaAllarmi();
		}
		onCreate = false;
	}
	private DecodificaPagina recuperaDati() throws Exception {
		DecodificaPagina previsione = new DecodificaPagina(this);
		if ((previsione.getBean() == null) || (previsione.getBean().alBean == null) || ((previsione.getBean().alBean.size() == 0))
				|| (previsione.getBean().alBean.get(0).data == null)) {
			previsione = null;
		}
		return previsione;
	}
	@Override
	public boolean stopService(Intent name) {
		return super.stopService(name);
	}

	public void onDestroy() {
		super.onDestroy();
		unregisterReceiver(br);
		if (timer != null) {
			timer.cancel();
		}
	}
}
